#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>
#include <QAbstractSocket>
const quint16 port = 6666;

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    tcpSocket =new QTcpSocket(this);
    ui->lineEdit_ip->setText("127.0.0.1");
    connect(ui->pushButton_connect,
            SIGNAL(clicked(bool))
            ,this,SLOT(ConnectServer()));

    connect(ui->pushButton_send,
            SIGNAL(clicked(bool))
            ,this,SLOT(sendMsg()));

}

Dialog::~Dialog()
{
  //  tcpSocket->close();
  //  delete tcpSocket;
    delete ui;
}


void Dialog::ConnectServer()
{
    QString ip= ui->lineEdit_ip->text();
    //1.如果连接了其他服务器 先关闭
    tcpSocket->abort();
    //连接服务器
    tcpSocket->connectToHost(ip ,port);
    //等待连接
    if(!tcpSocket->waitForConnected(200))
    {
        //断开连接
        tcpSocket->disconnectFromHost();
        qDebug()<< "连接服务器失败";
        tcpSocket->close();
        return ;
    }

    qDebug()<< "连接服务器 成功------";
    connect(tcpSocket, SIGNAL(readyRead())
            ,this,SLOT(readMsg()));

    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError))
            ,this,SLOT(showError(QAbstractSocket::SocketError)));

}

void Dialog::readMsg()
{
    QString str;
    str = tcpSocket->readAll();
    ui->textEdit->setText(str);
}

void Dialog::sendMsg()
{
    tcpSocket->write(ui->lineEdit_str->text().toLatin1());
    tcpSocket->flush();
}

void Dialog::showError(QAbstractSocket::SocketError)
{

   // qDebug()<<tcpSocket->errorString();
   // tcpSocket->disconnectFromHost();
  //  tcpSocket->close();
}
